<?php
class Block_Core_Form_Element_Tree
    extends Block_Core_Form_Element_Abstract
{
    public function _renderItem($item)
    {
        $html = '<ul>';
            foreach ($item as $_item) {
                $html .= '<li id="'.$_item['value'].'" ';
                if(array_key_exists($_item['value'], $this->getValue())) {
                    $html .= 'class="jstree-open jstree-checked"';
                }
                $html .='>';
                $html .= '<a href="#">'.$_item['label'].'</a>';
                if(isset($_item['chields'])) {
                    $html .= $this->_renderItem($_item['chields'],$html);
                }
                $html .= '</li>';
            }
        $html .= '</ul>';

        return $html;
    }

    public function toHtml()
    {
        $html = '<p><span';
        if($this->getRequired()) {
            $html .= ' class="req"';
        }
        $html .= '>';
        $html .= $this->getComment().'</span>';

        $html .= '<label>'.$this->getLabel();
        if($this->getRequired()) {
            $html .= '<span> (Required Field)</span>';
        }
        $html .= '</label>';

        $id = $this->getId()?$this->getId():microtime(true);
        $html .= '<div id="'.$id.'">';
        $html .= $this->_renderItem($this->getParams());
        $html .= '</div>';

        $html .= '<input type="hidden" id="'.$id.'_hidden" name="'.$this->getName().'"/>';

        $html .= '<script type="text/javascript">';
        $html .= 'jQuery(function () {
             jQuery("#'.$id.'").jstree({ 
                 "plugins" : [ "themes", "html_data", "checkbox" ],
                 "callback": {"check":'.$id.'_checked_function,"uncheck":'.$id.'_checked_function}
             });
             jQuery("#'.$id.'").jstree("set_theme","default");
             });

             function '.$id.'_checked_function() {
                 var arrayElements = jQuery(\'#'.$id.'\').jstree(\'get_checked\');
                 var stringValue = "";
                 arrayElements.each(function(el){
                     stringValue +=arrayElements[el].id+",";
                 });
                 $("'.$id.'_hidden").value = stringValue;
                 console.log($("'.$id.'_hidden").value);
             }
        </script>';
        $html .= '</p>';

        return $html;

    }
}